<template>
  <div class="user-management-container">
    <h2 class="page-title">用户管理</h2>
    
    <!-- 搜索和过滤 -->
    <el-card class="filter-card">
      <el-form :inline="true" :model="queryParams" class="filter-form">
        <el-form-item label="用户名">
          <el-input v-model="queryParams.username" placeholder="请输入用户名" clearable></el-input>
        </el-form-item>
        <el-form-item label="真实姓名">
          <el-input v-model="queryParams.realName" placeholder="请输入真实姓名" clearable></el-input>
        </el-form-item>
        <el-form-item label="角色">
          <el-select v-model="queryParams.role" placeholder="请选择角色" clearable>
            <el-option label="普通用户" :value="1"></el-option>
            <el-option label="商家" :value="2"></el-option>
            <el-option label="管理员" :value="3"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
            <el-option label="正常" :value="1"></el-option>
            <el-option label="禁用" :value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="handleQuery">查询</el-button>
          <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <!-- 用户列表 -->
    <el-card class="table-card">
      <div class="table-operations">
        <el-button type="danger" icon="el-icon-delete" :disabled="selectedUsers.length === 0" @click="handleBatchDelete">批量删除</el-button>
      </div>
      
      <el-table
        :data="userList"
        border
        stripe
        v-loading="loading"
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="id" label="ID" width="80"></el-table-column>
        <el-table-column prop="username" label="用户名" width="120"></el-table-column>
        <el-table-column prop="realName" label="真实姓名" width="120"></el-table-column>
        <el-table-column prop="phone" label="手机号" width="120"></el-table-column>
        <el-table-column prop="email" label="邮箱" width="180"></el-table-column>
        <el-table-column prop="role" label="角色" width="100">
          <template slot-scope="scope">
            <el-tag :type="getRoleTagType(scope.row.role)">{{ getRoleText(scope.row.role) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.status"
              :active-value="1"
              :inactive-value="0"
              @change="handleStatusChange(scope.row)">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="注册时间" width="180"></el-table-column>
        <el-table-column prop="lastLoginTime" label="最后登录时间" width="180"></el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="handleViewDetail(scope.row)">查看</el-button>
            <el-button type="text" size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="text" size="small" class="danger-btn" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="queryParams.size"
          :current-page="queryParams.page"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange">
        </el-pagination>
      </div>
    </el-card>
    
    <!-- 用户详情对话框 -->
    <el-dialog
      title="用户详情"
      :visible.sync="userDetailVisible"
      width="600px">
      <div v-if="currentUser" class="user-detail">
        <div class="user-avatar">
          <img :src="currentUser.avatar || 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'" alt="用户头像">
        </div>
        <div class="user-info">
          <el-descriptions :column="2" border>
            <el-descriptions-item label="ID">{{ currentUser.id }}</el-descriptions-item>
            <el-descriptions-item label="用户名">{{ currentUser.username }}</el-descriptions-item>
            <el-descriptions-item label="真实姓名">{{ currentUser.realName || '未设置' }}</el-descriptions-item>
            <el-descriptions-item label="手机号">{{ currentUser.phone }}</el-descriptions-item>
            <el-descriptions-item label="邮箱">{{ currentUser.email || '未设置' }}</el-descriptions-item>
            <el-descriptions-item label="角色">{{ getRoleText(currentUser.role) }}</el-descriptions-item>
            <el-descriptions-item label="状态">
              <el-tag :type="currentUser.status === 1 ? 'success' : 'danger'">
                {{ currentUser.status === 1 ? '正常' : '禁用' }}
              </el-tag>
            </el-descriptions-item>
            <!-- <el-descriptions-item label="性别">{{ getGenderText(currentUser.gender) }}</el-descriptions-item> -->
            <el-descriptions-item label="注册时间">{{ currentUser.createTime }}</el-descriptions-item>
            <el-descriptions-item label="最后登录时间">{{ currentUser.lastLoginTime || '未登录' }}</el-descriptions-item>
          </el-descriptions>
        </div>
      </div>
    </el-dialog>
    
    <!-- 编辑用户对话框 -->
    <el-dialog
      title="编辑用户"
      :visible.sync="editDialogVisible"
      width="500px">
      <el-form :model="editForm" :rules="editRules" ref="editForm" label-width="100px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="真实姓名" prop="realName">
          <el-input v-model="editForm.realName"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="editForm.phone"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="editForm.role" placeholder="请选择角色">
            <el-option label="普通用户" :value="1"></el-option>
            <el-option label="商家" :value="2"></el-option>
            <el-option label="管理员" :value="3"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="editForm.status">
            <el-radio :label="1">正常</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
          <!-- <el-form-item label="性别" prop="gender">
            <el-radio-group v-model="editForm.gender">
              <el-radio :label="1">男</el-radio>
              <el-radio :label="2">女</el-radio>
              <el-radio :label="0">未知</el-radio>
            </el-radio-group>
          </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitEdit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios'
import { getUserInfo, updateUserInfo } from '@/api/user'

export default {
  name: 'UserManagement',
  data() {
    return {
      // 查询参数
      queryParams: {
        page: 1,
        size: 10,
        username: '',
        realName: '',
        role: '',
        status: ''
      },
      // 用户列表
      userList: [],
      // 总记录数
      total: 0,
      // 加载状态
      loading: false,
      // 选中的用户
      selectedUsers: [],
      // 当前查看的用户
      currentUser: null,
      // 用户详情对话框可见性
      userDetailVisible: false,
      // 编辑对话框可见性
      editDialogVisible: false,
      // 编辑表单
      editForm: {
        id: null,
        username: '',
        realName: '',
        phone: '',
        email: '',
        role: 1,
        status: 1,
        gender: 0
      },
      // 编辑表单验证规则
      editRules: {
        phone: [
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
        ],
        email: [
          { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
        ],
        role: [
          { required: true, message: '请选择角色', trigger: 'change' }
        ]
      }
    }
  },
  created() {
    this.fetchUserList()
  },
  methods: {
    // 获取用户列表
    fetchUserList() {
      this.loading = true
      
      // 调用API获取用户列表
      const params = {
        page: this.queryParams.page,
        size: this.queryParams.size
      }
      
      if (this.queryParams.username) {
        params.username = this.queryParams.username
      }
      
      if (this.queryParams.realName) {
        params.realName = this.queryParams.realName
      }
      
      if (this.queryParams.role !== '') {
        params.role = this.queryParams.role
      }
      
      if (this.queryParams.status !== '') {
        params.status = this.queryParams.status
      }
      
      // 根据API文档 1.7 获取用户列表接口
      axios.get('/api/users', { params })
        .then(response => {
          if (response.code === 200) {
            this.userList = response.data
            this.total = response.total
          } else {
            this.$message.error(response.message || '获取用户列表失败')
          }
        })
        .catch(error => {
          console.error('获取用户列表失败', error)
          this.$message.error('获取用户列表失败')
        })
        .finally(() => {
          this.loading = false
        })
    },
    
    // 处理查询
    handleQuery() {
      this.queryParams.page = 1
      this.fetchUserList()
    },
    
    // 重置查询
    resetQuery() {
      this.queryParams = {
        page: 1,
        size: 10,
        username: '',
        realName: '',
        role: '',
        status: ''
      }
      this.fetchUserList()
    },
    
    // 处理选择变化
    handleSelectionChange(selection) {
      this.selectedUsers = selection
    },
    
    // 处理状态变化
    handleStatusChange(row) {
      const statusText = row.status === 1 ? '启用' : '禁用'
      this.$confirm(`确认要${statusText}用户"${row.username}"吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 根据API文档 1.6 更新用户状态接口
        axios.put(`/api/users/${row.id}/status?status=${row.status}`)
          .then(response => {
            if (response.code === 200) {
              this.$message.success(`${statusText}成功`)
            } else {
              row.status = row.status === 1 ? 0 : 1
              this.$message.error(response.message || `${statusText}失败`)
            }
          })
          .catch(error => {
            console.error(`${statusText}失败`, error)
            row.status = row.status === 1 ? 0 : 1
            this.$message.error(`${statusText}失败`)
          })
      }).catch(() => {
        // 取消操作，恢复原状态
        row.status = row.status === 1 ? 0 : 1
      })
    },
    
    // 查看用户详情
    handleViewDetail(row) {
      // 根据API文档 1.3 获取用户信息接口
      getUserInfo(row.id)
        .then(response => {
          if (response.code === 200) {
            this.currentUser = response.data
            this.userDetailVisible = true
          } else {
            this.$message.error(response.message || '获取用户详情失败')
          }
        })
        .catch(error => {
          console.error('获取用户详情失败', error)
          this.$message.error('获取用户详情失败')
        })
    },
    
    // 编辑用户
    handleEdit(row) {
      // 根据API文档 1.3 获取用户信息接口
      getUserInfo(row.id)
        .then(response => {
          if (response.code === 200) {
            const userData = response.data
            this.editForm = {
              id: userData.id,
              username: userData.username,
              realName: userData.realName || '',
              phone: userData.phone,
              email: userData.email || '',
              role: userData.role,
              status: userData.status,
              gender: userData.gender
            }
            this.editDialogVisible = true
          } else {
            this.$message.error(response.message || '获取用户信息失败')
          }
        })
        .catch(error => {
          console.error('获取用户信息失败', error)
          this.$message.error('获取用户信息失败')
        })
    },
    
    // 提交编辑
    submitEdit() {
      this.$refs.editForm.validate(valid => {
        if (valid) {
          // 根据API文档 1.5 更新用户信息接口
          updateUserInfo(this.editForm.id, {
            phone: this.editForm.phone,
            email: this.editForm.email,
            realName: this.editForm.realName,
            // gender: this.editForm.gender,
            role: this.editForm.role,
            status: this.editForm.status
          })
            .then(response => {
              if (response.code === 200) {
                this.$message.success('用户信息更新成功')
                this.editDialogVisible = false
                this.fetchUserList()
              } else {
                this.$message.error(response.message || '用户信息更新失败')
              }
            })
            .catch(error => {
              console.error('用户信息更新失败', error)
              this.$message.error('用户信息更新失败')
            })
        } else {
          return false
        }
      })
    },
    
    // 删除用户
    handleDelete(row) {
      this.$confirm(`确认要删除用户"${row.username}"吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 根据API文档 1.12 删除用户接口
        axios.delete(`/api/users/${row.id}`)
          .then(response => {
            if (response.code === 200) {
              this.$message.success('删除成功')
              this.fetchUserList()
            } else {
                  this.$message.error(response.message || '删除失败')
            }
          })
          .catch(error => {
            console.error('删除失败', error)
            this.$message.error('删除失败')
          })
      }).catch(() => {
        // 取消删除操作
      })
    },
    
    // 批量删除
    handleBatchDelete() {
      const usernames = this.selectedUsers.map(user => user.username).join('、')
      this.$confirm(`确认要删除选中的${this.selectedUsers.length}个用户(${usernames})吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // API文档中没有批量删除用户的接口，这里需要循环调用单个删除接口
        const deletePromises = this.selectedUsers.map(user => {
          return axios.delete(`/api/users/${user.id}`)
        })
        
        Promise.all(deletePromises)
          .then(() => {
            this.$message.success('批量删除成功')
            this.fetchUserList()
          })
          .catch(error => {
            console.error('批量删除失败', error)
            this.$message.error('批量删除失败')
            this.fetchUserList()
          })
      }).catch(() => {
        // 取消删除操作
      })
    },
    
    // 处理每页大小变化
    handleSizeChange(size) {
      this.queryParams.size = size
      this.fetchUserList()
    },
    
    // 处理页码变化
    handleCurrentChange(page) {
      this.queryParams.page = page
      this.fetchUserList()
    },
    
    // 获取角色标签类型
    getRoleTagType(role) {
      const types = {
        1: '',          // 普通用户
        2: 'success',   // 商家
        3: 'danger'     // 管理员
      }
      return types[role] || ''
    },
    
    // 获取角色文本
    getRoleText(role) {
      const texts = {
        1: '普通用户',
        2: '商家',
        3: '管理员'
      }
      return texts[role] || '未知角色'
    },
    
    // 获取性别文本
    getGenderText(gender) {
      const texts = {
        0: '未知',
        1: '男',
        2: '女'
      }
      return texts[gender] || '未知'
    }
  }
}
</script>

<style scoped>
.user-management-container {
  padding: 20px;
}

.page-title {
  margin-bottom: 20px;
  font-size: 24px;
  font-weight: bold;
}

.filter-card {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.table-operations {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.danger-btn {
  color: #F56C6C;
}

.user-detail {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.user-avatar {
  margin-bottom: 20px;
}

.user-avatar img {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  object-fit: cover;
}

.user-info {
  width: 100%;
}
</style>